package com.bpz.jxw.user.interceptor;

import com.alibaba.fastjson.JSON;
import com.bpz.jxw.user.annotation.CheckLogin;
import com.bpz.jxw.user.service.impl.UserService;
import com.bpz.main.bean.ReturnValueType;
import com.bpz.main.model.ActMsg;
import com.bpz.utils.PropCnfg;
import com.bpz.utils.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by 半瓶子 on 3/2/15.
 * blog: xusir.cnblogs.com
 */
public class UserInterceptor extends HandlerInterceptorAdapter {
    //@Autowired
    //IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (!(o instanceof HandlerMethod)) {
            return true;
        }
        Method currentMethod = ((HandlerMethod) o).getMethod();
        if (currentMethod.isAnnotationPresent(CheckLogin.class)) {
            ActMsg msg = new ActMsg();
            CheckLogin checkLogin = currentMethod.getAnnotation(CheckLogin.class);
            if (UserService.getLoginUser() == null) {
                if (ReturnValueType.JsonOrString.equals(checkLogin.returnValue())) {
                    msg.setCode(ActMsg.NOLOGIN);
                    msg.setMsg(PropCnfg.getVal("notLogin"));
                    StringUtils.write(response, JSON.toJSONString(msg));
                }else {
                    response.sendRedirect(checkLogin.url());
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
